package com.derbysoft.synxisadapter.action.settings.user;

import com.derbysoft.synxisadapter.action.BaseAdapterAction;
import com.derbysoft.synxisadapter.commons.model.User;
import com.opensymphony.xwork2.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.util.Arrays;

@Results(value = {
        @Result(name = Action.SUCCESS, location = "/page/settings/user/Edit.ftl")
})
public class EditAction extends BaseAdapterAction {
    private User user;

    private String userName;

    private String[] roleNames;

    public String execute() throws Exception {
        user = userRepository.findByName(userName);
        return SUCCESS;
    }

    public User getUser() {
        return user;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String ajaxSubmit() {
        try {
            userRepository.saveRoles(userName, roleNames);
            return populateSucceededJsonResult(null);
        } catch (Exception e) {
            return populateFailedJsonResult(e);
        }
    }

    public void setRoleNames(String[] roleNames) {
        if (roleNames != null) {
            this.roleNames = Arrays.copyOf(roleNames, roleNames.length);
        }
    }
}